import 'package:family_expense/features/account_user/models/user_active_token.dart';
import 'package:family_expense/features/account_user/services/user_active_token_service.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class LoginDeviceList extends StatefulWidget {
  const LoginDeviceList({super.key});

  @override
  State<LoginDeviceList> createState() => _LoginDeviceListState();
}

class _LoginDeviceListState extends State<LoginDeviceList> {
  final UserActiveTokenService _userActiveTokenService =
      UserActiveTokenService();

  List<UserActiveToken>? _list;
  String? _deviceId;

  @override
  void initState() {
    super.initState();

    _getCurrentDeviceId();
    _queryDevices();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: _buildBody());
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(title: const Text('登录设备'));
  }

  /// Builds main body.
  Widget _buildBody() {
    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            '以下是所有登录过的设备以及相关信息。移除，将需要在该设备上重新验证身份；禁用，将禁止从该设备再次登录和访问。',
            style: Theme.of(context).textTheme.bodySmall!,
          ),
        ),
        _buildDeivceList(),
      ],
    );
  }

  Widget _buildDeivceList() {
    if (_list == null) {
      return const MyPageTopCenterLoadingIndicator();
    }

    return Expanded(
      child: ListView(
        children: _list!
            .map(
              (e) => ListTile(
                title: Text(e.deviceModel!),
                subtitle: Text(
                  e.lastUpdated.formatDate(DatePatterns.longDateTime),
                ),
                trailing: Text(_getTrailingText(e)),
                selected: _deviceId == e.deviceId,
                onTap: _deviceId == e.deviceId
                    ? null
                    : () => _showActionMenu(e),
              ),
            )
            .toList(),
      ),
    );
  }

  String _getTrailingText(UserActiveToken userActiveToken) {
    var text = '';

    if (_deviceId == userActiveToken.deviceId) {
      text += '本机';
    } else if (!userActiveToken.enabled!) {
      text += '已禁用';
    }

    return text;
  }

  Future<void> _getCurrentDeviceId() async {
    _deviceId = await getDeviceId();
  }

  /// Queries all active devices for current user.
  Future<void> _queryDevices() async {
    final res = await _userActiveTokenService.queryDeviceByUsername();

    if (mounted) {
      setState(() => _list = res);
    }
  }

  void _showActionMenu(UserActiveToken userActiveToken) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return getSelectionBottomSheetContent([
          ListTile(
            leading: const Icon(Icons.delete),
            title: const Text('移除'),
            subtitle: const Text('移除后将需要在该设备上重新验证身份'),
            onTap: () {
              showConfirmDialog(
                context,
                '确定移除？',
                onConfirm: () {
                  _userActiveTokenService.delete(userActiveToken.id!).then((_) {
                    if (context.mounted) {
                      setState(() => _list!.remove(userActiveToken));

                      NavigatorHelper.pop(context);
                    }
                  });
                },
              );
            },
          ),
          ListTile(
            leading: userActiveToken.enabled!
                ? const Icon(Icons.lock)
                : const Icon(Icons.lock_open),
            title: userActiveToken.enabled!
                ? const Text('禁用')
                : const Text('恢复'),
            subtitle: userActiveToken.enabled!
                ? const Text('将禁止从该设备再次登录和访问')
                : const Text('将恢复该设备的登录和访问'),
            onTap: () {
              showConfirmDialog(
                context,
                userActiveToken.enabled! ? '确定禁用？' : '确定恢复？',
                onConfirm: () async {
                  final enabled = !userActiveToken.enabled!;

                  _userActiveTokenService.updateEnabled(
                    userActiveToken.id!,
                    enabled,
                  );

                  if (mounted) {
                    setState(() => userActiveToken.enabled = enabled);

                    NavigatorHelper.pop(context);
                  }
                },
              );
            },
          ),
        ], isHoriz: false);
      },
    );
  }
}
